package app.fugema.shop.main.login.view;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.base.common.app.LoginUtils;
import com.base.common.model.http.err.ApiException;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.Base64Utils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.VerifyUtils;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewObserver;
import app.fugema.shop.R;
import app.fugema.shop.databinding.FragmentBindPhoneBinding;
import app.fugema.shop.main.login.model.CheckImgResult;
import app.fugema.shop.main.login.vm.LoginVM;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

/**
 * 绑定手机号
 */
public class BindPhoneFragment extends BaseFragment<FragmentBindPhoneBinding, LoginVM>
{

    //图片验证码
    private CheckImgResult imgCodeResult;

    private  String userKey ;

    public static BindPhoneFragment newInstance() {
        Bundle args = new Bundle();
        BindPhoneFragment fragment = new BindPhoneFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected FragmentBindPhoneBinding initDataBinding(LayoutInflater inflater, ViewGroup container) {
        return DataBindingUtil.inflate(inflater, R.layout.fragment_bind_phone, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void initView()
    {
        super.initView();

        //发送验证码
        binding.btnSendCode.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                String phoneNum = binding.etPhoneNO.getText().toString();
                String imgCode = binding.etImgCode.getText().toString();
                if( UIUtils.isEmpty(imgCode) )
                {
                   UIUtils.showToastSafes("请输入验证码");
                   return;
                }
                if (!phoneNum.isEmpty())
                {
                    LogUtil.e( phoneNum );
                    getVerfyCode(phoneNum,imgCode);
                } else {
                    UIUtils.showToastSafes("手机号不能为空");
                }
            }
        });

        //立即绑定
        binding.btnBind.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                nextStep();
            }
        });
        // 点击 图片验证码 切换
        binding.ivImgCode.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                getImgVerfyCode();
            }
        });


        //手机号
        binding.etPhoneNO.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    binding.btnSendCode.setEnabled(false);
                    binding.btnSendCode.setAlpha(0.6f);
                } else {
                    binding.btnSendCode.setEnabled(true);
                    binding.btnSendCode.setAlpha(1f);
                }
            }
        });
        VerifyUtils.onTextChangedPhone(binding.etPhoneNO);
        String s = binding.etPhoneNO.getText().toString().trim();
        if (s.length() == 0)
        {
            binding.btnSendCode.setEnabled(false);
            binding.btnSendCode.setAlpha(0.6f);
        }

        //填写了验证码 才能点击 立即绑定
        binding.etMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    binding.btnBind.setEnabled(false);
                    binding.btnBind.setAlpha(0.6f);
                } else {
                    binding.btnBind.setEnabled(true);
                    binding.btnBind.setAlpha(1f);
                }
            }
        });

    }

    @Override
    public void initData()
    {
        super.initData();
        userKey = LoginUtils.getToken();
        //先获取图片 验证码
        getImgVerfyCode();
    }

    /***
     * 下一步，校验验证码
     */
    private void nextStep()
    {
        String phoneNum = binding.etPhoneNO.getText().toString().replaceAll(" ", "");
        String msgCode = binding.etMsgCode.getText().toString();

        if (phoneNum.isEmpty())
        {
            UIUtils.showToastSafes("手机号不能为空");
            return;
        }

        if (msgCode.isEmpty())
        {
            UIUtils.showToastSafes("验证码不能为空");
            return;
        }

        viewModel.checkBindTelVerfyCode(phoneNum, msgCode ,userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity()) {
                    @Override
                    protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                    {
                        if( data.data.isSuccess() )
                        {
                            if (getActivity() instanceof BindPhoneActivity)
                            {
                                BindPhoneActivity bindAty = (BindPhoneActivity) getActivity();
                                bindAty.setResultTips("绑定成功！");
                            }
                        }
                    }

                    @Override
                    protected void onError(ApiException error) {
                        super.onError(error);
                        UIUtils.showToastSafes(error.getMessage());
                    }
                });
    }


    /**
     * 获取验证码
     *
     * @param phoneNum
     */
    private void getVerfyCode(String phoneNum,String imgCode)
    {

        viewModel.getBindTelVerfyCode(phoneNum , userKey,imgCode,imgCodeResult.getId())
                 .observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity())
                 {
                    @Override
                    protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                    {
                        //{"success":false,
                        //    "msg":"请输入图形验证码",
                        //    "code":0}
                        starTimeCountDown();
                        UIUtils.showToastSafes(data.data.getMsg());
                    }

                    @Override
                    protected void onError(ApiException error)
                    {
                        UIUtils.showToastSafes(error.getMessage());
                    }
                });
    }

    private void getImgVerfyCode()
    {
        viewModel.getImgCheckCode()
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CheckImgResult>>()
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<CheckImgResult> data)
                     {
                         if( UIUtils.isNotEmpty( data.data.getFileContents() ) )
                         {
                             imgCodeResult = data.data;
                             //LogUtil.e( data.data.getFileContents() );
                             // 显示 图片验证码
                             binding.ivImgCode.setImageBitmap( Base64Utils.base64ToBitmap(data.data.getFileContents()) );
                         }
                     }


                     @Override
                     public boolean isEmptyData(LiveDataWrapper<CheckImgResult> data)
                     {
                         return UIUtils.isEmpty( data.data );
                     }
                 });
    }



    private final int mTotalCountDown = 60 * 1000;
    private CountDownTimer mCountDownTimer;

    /**
     * 开始倒计时
     */
    private void starTimeCountDown() {
        binding.btnSendCode.setEnabled(false);
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(mTotalCountDown, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    binding.btnSendCode.setText((millisUntilFinished / 1000) + "s");
                }

                @Override
                public void onFinish() {
                    binding.btnSendCode.setEnabled(true);
                    binding.btnSendCode.setText("获取验证码");
                }
            };
        }
        mCountDownTimer.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }
}
